import sparkMd5 from './spark-md5';
import api from './api';
const MAX_UPLOAD_SIZE = 20 * 1024 * 1024; // 10M

//直连图片服务器上传
export const uploadTempFile = (tempFilePath:any) => {
  return new Promise((resolve, reject) => {
    // let tempFilePath = tempFile.tempFilePath;
    let fs = wx.getFileSystemManager();
    let fd = fs.openSync({
      filePath: tempFilePath
    });
    let stat = fs.fstatSync({
      fd: fd
    });
    let arr = tempFilePath.split('.');
    let size = stat.size;
    if (size > MAX_UPLOAD_SIZE) {
      reject('文件过大，不能上传');
      return;
    }
    let ab = new ArrayBuffer(size);
    let result = fs.readSync({
      fd: fd,
      arrayBuffer: ab,
      position: 0,
      length: size
    });
    let arrayBuffer = result.arrayBuffer;
    fs.closeSync({
      fd: fd
    });
    var spark = new sparkMd5.ArrayBuffer();
    spark.append(arrayBuffer);
    let md5 = spark.end(false);
    api.image.getUploadParam({
      filename: tempFilePath,
      contentMd5: md5,
      contentLength: size
    }).then((res:any) => {
      if (res.data.code !== '000') {
        reject('上传失败');
        return;
      }
      wx.request({
        url: res.data.data.url,
        method: res.data.data.method,
        header: res.data.data.headers,
        data: arrayBuffer,
        success(uploadRes) {
          resolve({
            filepath: res.data.data.filepath,
            readUrl: res.data.data.readUrl
          })
        },
        fail() {
          reject('上传失败');
        }
      })
    })
  });
}